<!-- src/components/class-center/ClassNotice.vue -->
<template>
  <div class="class-notice">
    <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
      <!-- 我收到的通知 -->
      <el-tab-pane label="我收到的" name="received">
        <div class="tab-content">
          <!-- 筛选区域 -->
          <div class="filter-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="filter-item">
                  <span class="filter-label">通知类型：</span>
                  <el-select
                      v-model="filters.typeId"
                      placeholder="全部类型"
                      clearable
                      @change="handleFilterChange"
                  >
                    <el-option
                        v-for="type in noticeTypes"
                        :key="type.typeId"
                        :label="type.typeName"
                        :value="type.typeId"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="16">
                <div class="filter-item" style="justify-content: flex-end;">
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="handleReset">重置</el-button>
                  <el-button type="success" @click="handleCreateNotice">
                    <el-icon><Plus /></el-icon>
                    发布通知
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 通知列表 -->
          <div class="notice-list">
            <el-table
                :data="receivedNotices"
                stripe
                style="width: 100%"
                v-loading="loading"
                empty-text="暂无通知"
            >
              <el-table-column prop="title" label="通知标题" min-width="200">
                <template #default="{ row }">
                  <div class="notice-title">
                    <el-tag
                        v-if="!row.readStatus"
                        size="small"
                        type="danger"
                        style="margin-right: 8px"
                    >
                      新
                    </el-tag>
                    <span
                        :class="{ 'unread-title': !row.readStatus }"
                        @click="handleViewNotice(row)"
                        style="cursor: pointer; color: #409EFF;"
                    >
                      {{ row.title }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="typeName" label="类型" width="100" align="center" />
              <el-table-column prop="senderName" label="发布人" width="120" align="center" />
              <el-table-column prop="createTime" label="发布时间" width="180" align="center">
                <template #default="{ row }">
                  {{ formatDateTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="readStatus" label="状态" width="80" align="center">
                <template #default="{ row }">
                  <el-tag
                      :type="row.readStatus ? 'success' : 'warning'"
                      size="small"
                  >
                    {{ row.readStatus ? '已读' : '未读' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleViewNotice(row)"
                  >
                    查看
                  </el-button>
                  <el-button
                      link
                      type="danger"
                      size="small"
                      @click="handleDeleteNotice(row, 'received')"
                      v-if="false"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="receivedPagination.total > receivedPagination.pageSize">
            <el-pagination
                v-model:current-page="receivedPagination.currentPage"
                v-model:page-size="receivedPagination.pageSize"
                :page-sizes="[10, 20, 50]"
                :total="receivedPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <!-- 我发布的通知 -->
      <el-tab-pane label="我发布的" name="published">
        <div class="tab-content">
          <!-- 筛选区域 -->
          <div class="filter-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="filter-item">
                  <span class="filter-label">通知类型：</span>
                  <el-select
                      v-model="filters.typeId"
                      placeholder="全部类型"
                      clearable
                      @change="handleFilterChange"
                  >
                    <el-option
                        v-for="type in noticeTypes"
                        :key="type.typeId"
                        :label="type.typeName"
                        :value="type.typeId"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="16">
                <div class="filter-item" style="justify-content: flex-end;">
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="handleReset">重置</el-button>
                  <el-button type="success" @click="handleCreateNotice">
                    <el-icon><Plus /></el-icon>
                    发布通知
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 通知列表 -->
          <div class="notice-list">
            <el-table
                :data="publishedNotices"
                stripe
                style="width: 100%"
                v-loading="loading"
                empty-text="暂无发布的通知"
            >
              <el-table-column prop="title" label="通知标题" min-width="200">
                <template #default="{ row }">
                  <div class="notice-title">
                    <el-tag
                        v-if="row.readCount !== row.totalRecipients"
                        size="small"
                        type="warning"
                        style="margin-right: 8px"
                    >
                      未全读
                    </el-tag>
                    <span
                        :class="{ 'unread-title': row.readCount !== row.totalRecipients }"
                        @click="handleViewNotice(row)"
                        style="cursor: pointer; color: #409EFF;"
                    >
                      {{ row.title }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="typeName" label="类型" width="100" align="center" />
              <el-table-column prop="recipientInfo" label="接收对象" width="150" align="center">
                <template #default="{ row }">
                  <el-tooltip :content="row.recipientInfo" placement="top">
                    <span style="cursor: help;">{{ truncateText(row.recipientInfo, 8) }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="发布时间" width="180" align="center">
                <template #default="{ row }">
                  {{ formatDateTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="readCount" label="已读/总数" width="100" align="center">
                <template #default="{ row }">
                  <span :class="{ 'all-read': row.readCount === row.totalRecipients }">
                    {{ row.readCount }}/{{ row.totalRecipients }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleViewNotice(row)"
                  >
                    查看
                  </el-button>
                  <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleEditNotice(row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                      link
                      type="danger"
                      size="small"
                      @click="handleDeleteNotice(row, 'published')"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="publishedPagination.total > publishedPagination.pageSize">
            <el-pagination
                v-model:current-page="publishedPagination.currentPage"
                v-model:page-size="publishedPagination.pageSize"
                :page-sizes="[10, 20, 50]"
                :total="publishedPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 通知详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="currentNotice?.title"
        width="60%"
        :before-close="handleCloseDialog"
    >
      <NoticeDetail
          v-if="currentNotice"
          :notice="currentNotice"
          :tab-type="activeTab"
          @close="detailDialogVisible = false"
          @edit="handleEditFromDetail"
          @delete="handleDeleteFromDetail"
      />
    </el-dialog>

    <!-- 发布/编辑通知对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="isEditing ? '编辑通知' : '发布通知'"
        width="70%"
        :before-close="handleCloseEditDialog"
    >
      <NoticeEditForm
          v-if="editDialogVisible"
          :notice-data="currentNotice"
          :is-editing="isEditing"
          @success="handleEditSuccess"
          @cancel="editDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import NoticeDetail from './NoticeDetail.vue'
import NoticeEditForm from './NoticeEditForm.vue'
import {
  fetchNotices,
  fetchNoticeTypes,
  markNoticeAsRead,
  deleteNotice,
  createNotice,
  updateNotice
} from '@/api/teacher'

// 接口定义 - 拆分为精确类型
interface ReceivedNoticeItem {
  noticeId: number
  title: string
  typeId: number
  typeName: string
  description: string
  content: string
  senderName: string
  createTime: string
  readStatus: boolean
}

interface PublishedNoticeItem {
  noticeId: number
  title: string
  typeId: number
  typeName: string
  description: string
  content: string
  senderName: string
  createTime: string
  readCount: number
  totalRecipients: number
  recipientInfo: string
  scheduleId?: number
}

interface NoticeType {
  typeId: number
  typeName: string
  description: string
}

interface Filters {
  typeId: number | null
  readStatus: string | null
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const activeTab = ref('received')
const loading = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const isEditing = ref(false)

const receivedNotices = ref<ReceivedNoticeItem[]>([])
const publishedNotices = ref<PublishedNoticeItem[]>([])
const noticeTypes = ref<NoticeType[]>([])

// 使用联合类型
const currentNotice = ref<ReceivedNoticeItem | PublishedNoticeItem | null>(null)

const filters = reactive<Filters>({
  typeId: null,
  readStatus: null
})

const receivedPagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const publishedPagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const currentPagination = computed(() =>
    activeTab.value === 'received' ? receivedPagination : publishedPagination
)

// 方法
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  handleSearch()
}

const handleFilterChange = () => {
  currentPagination.value.currentPage = 1
  loadNotices()
}

const handleSearch = () => {
  currentPagination.value.currentPage = 1
  loadNotices()
}

const handleReset = () => {
  filters.typeId = null
  filters.readStatus = null
  handleSearch()
}

const handleSizeChange = (size: number) => {
  currentPagination.value.pageSize = size
  loadNotices()
}

const handleCurrentChange = (page: number) => {
  currentPagination.value.currentPage = page
  loadNotices()
}

const handleCreateNotice = () => {
  currentNotice.value = null
  isEditing.value = false
  editDialogVisible.value = true
}

const handleViewNotice = async (notice: ReceivedNoticeItem | PublishedNoticeItem) => {
  currentNotice.value = notice
  detailDialogVisible.value = true

  // 标记为已读（如果是收到的通知）
  if (activeTab.value === 'received' && 'readStatus' in notice && !notice.readStatus) {
    await markAsRead(notice.noticeId)
  }
}

const handleEditNotice = (notice: PublishedNoticeItem) => {
  currentNotice.value = notice
  isEditing.value = true
  editDialogVisible.value = true
}

const handleEditFromDetail = (notice: ReceivedNoticeItem | PublishedNoticeItem) => {
  handleCloseDialog()
  // 只有发布的通知才能编辑
  if ('totalRecipients' in notice) {
    handleEditNotice(notice)
  }
}

const handleDeleteFromDetail = (notice: ReceivedNoticeItem | PublishedNoticeItem) => {
  handleCloseDialog()
  const tabType = activeTab.value === 'received' ? 'received' : 'published'
  handleDeleteNotice(notice, tabType)
}

const handleDeleteNotice = async (notice: ReceivedNoticeItem | PublishedNoticeItem, tabType: string) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除通知"${notice.title}"吗？`,
        '删除确认',
        {
          app: undefined,
          components: undefined,
          config: undefined,
          directives: undefined,
          mixins: [],
          provides: undefined,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    const userInfoStr = localStorage.getItem('userInfo')
    const userInfo = JSON.parse(userInfoStr)
    // 调用删除API
    const response = await deleteNotice(notice.noticeId, userInfo.id)
    if (response.success) {
      ElMessage.success('删除成功')
      await loadNotices()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.log('取消删除')
  }
}

const handleCloseDialog = () => {
  detailDialogVisible.value = false
  currentNotice.value = null
}

const handleCloseEditDialog = () => {
  editDialogVisible.value = false
  currentNotice.value = null
}

const handleEditSuccess = async (result: any) => {
  editDialogVisible.value = false
  ElMessage.success(isEditing.value ? '通知更新成功' : '通知发布成功')
  await loadNotices()
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const truncateText = (text: string, length: number) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

const markAsRead = async (noticeId: number) => {
  try {
    // 从localStorage获取用户ID
    const userInfoStr = localStorage.getItem('userInfo')
    let userId = ''

    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userId = userInfo.id || ''
      } catch (error) {
        console.error('解析用户信息失败', error)
      }
    }

    if (userId) {
      const response = await markNoticeAsRead(noticeId, parseInt(userId))
      if (response.success) {
        // 更新本地状态
        const notice = receivedNotices.value.find(n => n.noticeId === noticeId)
        if (notice) {
          notice.readStatus = true
        }
      }
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

// 加载数据
const loadNotices = async () => {
  loading.value = true
  try {
    // 从localStorage获取用户ID
    const userInfoStr = localStorage.getItem('userInfo')
    let userId = ''

    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userId = userInfo.id || ''
      } catch (error) {
        console.error('解析用户信息失败', error)
      }
    }

    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录')
      return
    }

    const response = await fetchNotices(
        parseInt(userId),
        activeTab.value as 'received' | 'published',
        filters.typeId || undefined,
        currentPagination.value.currentPage,
        currentPagination.value.pageSize
    )

    if (response.success) {
      if (activeTab.value === 'received') {
        receivedNotices.value = response.data || []
        receivedPagination.total = response.data?.length || 0
      } else {
        publishedNotices.value = response.data || []
        publishedPagination.total = response.data?.length || 0
      }
    } else {
      ElMessage.error(response.message || '获取通知列表失败')
      // API调用失败时清空数据
      if (activeTab.value === 'received') {
        receivedNotices.value = []
        receivedPagination.total = 0
      } else {
        publishedNotices.value = []
        publishedPagination.total = 0
      }
    }
  } catch (error) {
    console.error('加载通知失败:', error)
    ElMessage.error('加载通知失败')
    // 清空数据
    if (activeTab.value === 'received') {
      receivedNotices.value = []
      receivedPagination.total = 0
    } else {
      publishedNotices.value = []
      publishedPagination.total = 0
    }
  } finally {
    loading.value = false
  }
}

const loadNoticeTypes = async () => {
  try {
    const response = await fetchNoticeTypes()
    if (response.success) {
      noticeTypes.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取通知类型失败')
      noticeTypes.value = []
    }
  } catch (error) {
    console.error('加载通知类型失败:', error)
    noticeTypes.value = []
  }
}

// 初始化加载
const initData = async () => {
  await Promise.all([
    loadNoticeTypes(),
    loadNotices()
  ])
}

// 生命周期
onMounted(() => {
  initData()
})
</script>

<style scoped>
.class-notice {
  padding: 0;
}

.tab-content {
  padding: 0;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  width:180px;
  text-align: right;
  margin-right: 10px;
  font-weight: 500;
}

.notice-list {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: right;
}

.notice-title {
  display: flex;
  align-items: center;
}

.unread-title {
  font-weight: 600;
}

.all-read {
  color: #67C23A;
  font-weight: 600;
}

:deep(.el-table .cell) {
  text-align: center;
}

:deep(.el-table th > .cell) {
  font-weight: 600;
}
</style>
